package controller;


 
import sun.misc.BASE64Encoder;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;

/**
 * 生成图片验证码，并给前端浏览器返回
 * 画画
 * 画笔
 * 画布
 */
@WebServlet("/checkCode")
public class ValidateServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//创建一个画布
		BufferedImage image=new BufferedImage(200, 30, BufferedImage.TYPE_3BYTE_BGR);
		Graphics2D g=(Graphics2D) image.getGraphics();
		//设置画笔颜色
		g.setColor(new Color(
				new Random().nextInt(255),
				new Random().nextInt(255),
				new Random().nextInt(255)
		));
		//通过画笔来填充画布颜色
		g.fillRect(0, 0, 200, 30);
		//重新设置画笔颜色
		for(int i=0;i<5;i++) {
			g.setColor(new Color(
					new Random().nextInt(255),
					new Random().nextInt(255),
					new Random().nextInt(255)));
			int x1=new Random().nextInt(200);
			int y1=new Random().nextInt(30);
			int x2=new Random().nextInt(200);
			int y2=new Random().nextInt(30);
			g.drawLine(x1, y1, x2, y2);
		}
		//重新设置字体字形字号
		Font font=new Font("楷体",Font.BOLD,25);
		g.setFont(font);
		// 设置验证码的字典
		String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		String checkCode="";
		Random ran = new Random();
		//5位数随机验证码的拼接
		for (int i = 1; i <=5; i++) {
			int index = ran.nextInt(str.length());
			// 获取字符
			char ch = str.charAt(index);// str就是随机字符
			checkCode=checkCode+ch;
		}
		int x=50;
		int y=20;
		for(int i=0;i<checkCode.length();i++) {
			char c=checkCode.charAt(i);
			//随机生成0-60°之间角度
			int degree=new Random().nextInt(120)-60;
			//设置旋转
			g.rotate(Math.PI/180*degree,x,y);
			g.drawString(c+"", x, y);
			g.rotate(-Math.PI/180*degree,x,y);
			x+=20;
		}
		//创建会话
		HttpSession session=req.getSession(true);
		//每次都要刷新一下验证码，刷新后存入session，验证由其余部分实现
		session.setAttribute("checkCode",checkCode);
		//响应数据类型
		ByteArrayOutputStream out = new ByteArrayOutputStream();//io流
		ImageIO.write(image, "png", out);//写入流中
		byte[] bytes = out.toByteArray();//转换成字节
		BASE64Encoder encoder = new BASE64Encoder();
		String png_base64 =  encoder.encodeBuffer(bytes);//转换成base64串
		png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
		resp.getWriter().write("data:image/"+ "png" +";base64,"+png_base64);

	}
}


